﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMS.BLL;
using PMS.Entity;
using PMS.Resources;
using PMS.Win;
using PMS.Utils;
using DevExpress.XtraEditors.Mask;
using PMS.DanhMucChung;
using System.Collections.Generic;
using PMS.ValidationRules;
using PMS.ReportViewer;
using DevExpress.XtraGrid.Views.Base;

namespace PMS.ChucNang
{
    public partial class NhapKhoEntry : FormEntryBase
    {
        #region Constants
        private const string PRODUCT_NOT_EXIST = "PRODUCT_NOT_EXIST";
        private const string INVALID_QUANTITY = "INVALID_QUANTITY";
        private const string CHITIETPHIEUNHAP_EXISTED = "CHITIETPHIEUNHAP_EXISTED";
        private const string DUPLICATE_PRODUCT_CODE = "DUPLICATE_PRODUCT_CODE";
        private const string MUST_FILL_HANDUNG_OR_HANSUDUNG = "MUST_FILL_HANDUNG_OR_HANSUDUNG";
        private const string DUPLICATE_SOLO = "DUPLICATE_SOLO";

        private string NEW_String = Messages.GetString(Constants.NEW);
        private const string BINDING_PROPERTY = "EditValue";
        #endregion

        #region Private Members
        BaseEntityCollection<ChiTietPhieuNhap> m_DetailItemsList;
        private List<ComboItemExp> m_KhoList;
        protected SanPhamBO m_ProductService;
        protected PhieuNhapBO m_Service;
        protected LuuKhoBO m_LuuKhoService;
        protected ChiTietPhieuNhapBO m_ChiTietService;
        private bool IsLastRowValid;
        
        protected bool m_isDuplicateProduct { get; set; }
        #endregion

        #region Properties
        protected Entity.PhieuNhap CurrentNhapKhoEntry
        {
            get
            {
                return base.Entity as Entity.PhieuNhap;
            }
            set
            {
                base.Entity = value;
            }
        }
        #endregion

        #region Services
        public PhieuNhapBO Service
        {
            get
            {
                if (m_Service == null)
                {
                    m_Service = new PhieuNhapBO();
                }
                return m_Service;
            }
        }

        public LuuKhoBO LuuKhoService
        {
            get
            {
                if (m_LuuKhoService == null)
                {
                    m_LuuKhoService = new LuuKhoBO();
                }
                return m_LuuKhoService;
            }
        }

        public SanPhamBO ProductService
        {
            get
            {
                if (m_ProductService == null)
                {
                    m_ProductService = new SanPhamBO();
                }
                return m_ProductService;
            }
        }

        public ChiTietPhieuNhapBO ChiTietService
        {
            get
            {
                if (m_ChiTietService == null)
                {
                    m_ChiTietService = new ChiTietPhieuNhapBO();
                }
                return m_ChiTietService;
            }
        }
        #endregion

        #region Constructors
        public NhapKhoEntry(string functionID)
            : base(functionID)
        {
            InitializeComponent();
            Init();
        }
        #endregion

        #region Init Data and Style
        private void Init()
        {
            InitData();
            InitStyle();
        }

        private void InitData()
        {
            m_DetailItemsList = new BaseEntityCollection<ChiTietPhieuNhap>();
            BindingToGrid();
            loadDatasourceCbbKho();
        }

        private void InitStyle()
        {
            //grid
            grdDetail.CausesValidation = false;
            bteMaPN.Tag = "Ignore";
            this.grvDetail.IndicatorWidth = Constants.INDICATOR_WIDTH;

            this.grvDetail.OptionsView.ShowFooter = false;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsView.ShowGroupPanel = false;
            this.grvDetail.OptionsCustomization.AllowColumnMoving = false;
            this.grvDetail.OptionsCustomization.AllowGroup = false;
            this.grvDetail.OptionsMenu.EnableColumnMenu = false;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsNavigation.EnterMoveNextColumn = true;
            this.grvDetail.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
            this.grvDetail.IndicatorWidth = Constants.INDICATOR_WIDTH;
            this.grvDetail.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

            cbbMaKho.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            cbbMaKho.Properties.ReadOnly = true;
            txtTongTien.Properties.ReadOnly = true;

            //filed color
            txtSoHD.BackColor = REQUIRED_FIELD_COLOR;
            dteNgayNhap.BackColor = REQUIRED_FIELD_COLOR;
            bteNhaCC.BackColor = REQUIRED_FIELD_COLOR;
            cbbMaKho.BackColor = REQUIRED_FIELD_COLOR;

            //Mask
            txtTongTien.Properties.Mask.MaskType = MaskType.Numeric;
            txtTongTien.Properties.Mask.EditMask = ConfigurationConstant.PositiveNumericFormatString;
            txtTongTien.Properties.Mask.UseMaskAsDisplayFormat = true;

            spdColSoLuong.Mask.MaskType = MaskType.Numeric;
            spdColSoLuong.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            spdColSoLuong.Mask.UseMaskAsDisplayFormat = true;

            calColDonGia.Mask.MaskType = MaskType.Numeric;
            calColDonGia.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            calColDonGia.Mask.UseMaskAsDisplayFormat = true;

            txtColTotal.Mask.MaskType = MaskType.Numeric;
            txtColTotal.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtColTotal.Mask.UseMaskAsDisplayFormat = true;

            this.bteMaPN.Properties.MaxLength = 14;
            this.txtSoHD.Properties.MaxLength = 12;
            this.bteNhaCC.Properties.MaxLength = 6;
            this.txtNguoiLap.Properties.MaxLength = 35;
            this.txtNguoiNhap.Properties.MaxLength = 35;
            this.txtLyDo.Properties.MaxLength = 200;
            this.txtGhiChu.Properties.MaxLength = 300;


        }
        #endregion

        #region override methods

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (this.CurrentNhapKhoEntry == null)
            {
                this.DoNew();
            }
        }

        protected override void BindingToControls(IBaseEntity entity)
        {
            base.BindingToControls(entity);

            this.bteMaPN.DataBindings.Clear();
            this.txtSoHD.DataBindings.Clear();
            this.bteNhaCC.DataBindings.Clear();
            this.txtNguoiLap.DataBindings.Clear();
            this.dteNgayLap.DataBindings.Clear();
            this.txtNguoiNhap.DataBindings.Clear();
            this.dteNgayNhap.DataBindings.Clear();
            this.txtLyDo.DataBindings.Clear();
            this.txtGhiChu.DataBindings.Clear();


            this.bteMaPN.DataBindings.Add(BINDING_PROPERTY, entity, PhieuNhapColumns.SoPN.ToString());
            this.txtSoHD.DataBindings.Add(BINDING_PROPERTY, entity, PhieuNhapColumns.SoHD.ToString());
            this.bteNhaCC.DataBindings.Add(BINDING_PROPERTY, entity, PhieuNhapColumns.MaNCC.ToString());
            this.txtNguoiLap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuNhapColumns.NguoiLap.ToString());
            this.dteNgayLap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuNhapColumns.NgayLapPhieu.ToString());
            this.txtNguoiNhap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuNhapColumns.NguoiNhap.ToString());
            this.dteNgayNhap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuNhapColumns.NgayNhapKho.ToString());
            this.txtLyDo.DataBindings.Add(BINDING_PROPERTY, entity, PhieuNhapColumns.LyDoNhap.ToString());
            this.txtGhiChu.DataBindings.Add(BINDING_PROPERTY, entity, PhieuNhapColumns.GhiChu.ToString());

            PhieuNhap pn = entity as PhieuNhap;
            m_DetailItemsList.Clear();
            m_DetailItemsList.AddRange(ChiTietService.GetAllChiTietPhieuNhapBySoPN(pn.SoPN));
            BindingToGrid();
            SetKhoCbbData(pn.MaKho);
            if (m_DetailItemsList.Count > 0)
            {
                decimal total = 0;
                foreach (ChiTietPhieuNhap item in m_DetailItemsList)
                {

                    total = total + item.Total;
                }
                txtTongTien.EditValue = total;
            }

           
        }

        protected override void FocusFirtsControl()
        {
            base.FocusFirtsControl();
            this.txtSoHD.Focus();
        }

        protected override void InitValidationRules()
        {
            base.InitValidationRules();
            
            Validator validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new DateValidateRule(true,true));
            SetValidator(validate, dteNgayNhap);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(base.CreateNotEmptyValidationRule());
            SetValidator(validate, txtSoHD);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new VendorValidationRules(null,true));
            SetValidator(validate, bteNhaCC);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new InventoryValidationRules(null, true));
            SetValidator(validate, cbbMaKho);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new PhieuNhapValidateRule(NEW_String, false));
            SetValidator(validate, bteMaPN);

        }

        public override void New()
        {
            this.CurrentNhapKhoEntry = new Entity.PhieuNhap
                {
                    NgayLapPhieu = Constants.BUSINESS_DATE,
                    NgayNhapKho = Constants.BUSINESS_DATE,
                    SoPN = NEW_String,
                    MaKho = "KHO01"
                };
            base.New();
        }
        public override void IsNewChanged()
        {
            if (IsNew)
            {
                CanPrint = false;
                grvDetail.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
                colMaThuoc.OptionsColumn.ReadOnly = false;
                colSoLo.OptionsColumn.ReadOnly = false;
                dteNgayNhap.Enabled = true;
                bteColMaThuoc.Buttons[0].Enabled = true;
            }
            else
            {
                CanPrint = true;
                grvDetail.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                colMaThuoc.OptionsColumn.ReadOnly = true;
                colSoLo.OptionsColumn.ReadOnly = true;
                dteNgayNhap.Enabled = false;
                bteColMaThuoc.Buttons[0].Enabled = false;
            }
        }
        protected override bool Save()
        {
            try
            {
                grvDetail_ValidateRow(this.grvDetail, new ValidateRowEventArgs(this.grvDetail.FocusedRowHandle,
                                                                             this.grvDetail.GetRow(this.grvDetail.FocusedRowHandle)));
                if (!IsLastRowValid)
                    return false;
                    ChiTietPhieuNhaps detailList = new ChiTietPhieuNhaps();
                    detailList.AddRange(m_DetailItemsList);
                    if (detailList.Count <= 0)
                    {
                        MessageBox.Show(this, "Vui lòng nhập vào thông tin Chi Tiết Phiếu Nhập", "Chú ý", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                    if (IsNew)
                    {
                        CurrentNhapKhoEntry = Service.CreatePhieuNhap(CurrentNhapKhoEntry, detailList);
                    }
                    else
                    {
                        Service.UpdatePhieuNhap(CurrentNhapKhoEntry, detailList);
                    }
                    return true;
                
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        protected override bool Delete()  //do not allow delete PhieuNhap
        {
            //try
            //{
            //    Service.DeletePhieuNhap(CurrentNhapKhoEntry);
            //    return true;
            //}
            //catch (Exception ex)
            //{
            //    ShowErrorMessage(ex);
            //    return false;
            //}
            MessageBox.Show(this, "Bạn không thể thực hiện được thao tác xóa Phiếu Nhập", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return false;
        }

        public override void Cancel()
        {
            //your code here
            base.Cancel();
        }

        protected override void Print()
        {
            try
            {
                PhieuNhapKhoViewer rpViewer = new PhieuNhapKhoViewer(CurrentNhapKhoEntry.SoPN);
                rpViewer.StartPosition = FormStartPosition.CenterParent;
                rpViewer.WindowState = FormWindowState.Maximized;
                rpViewer.ShowDialog();
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        protected override IBaseEntity GetEntity()
        {
            //need to get the latest record of the current Entity's ID or code then return it
            return base.GetEntity();
        }

        protected override void ClearData()
        {
            New();
        }
        #endregion

        #region Lookups
        #endregion

        #region Form's function

        private void BindingToGrid()
        {
            grdDetail.DataSource = m_DetailItemsList;
            colMaThuoc.FieldName = LuuKhoColumns.MaThuoc.ToString();
            colSoLuong.FieldName = ChiTietPhieuNhapColumns.SoLuong.ToString();
            colDonGia.FieldName = ChiTietPhieuNhapColumns.DonGia.ToString();
            colNgaySX.FieldName = LuuKhoColumns.NgaySX.ToString();
            colHanSuDung.FieldName = LuuKhoColumns.HanSuDung.ToString();
            colHanDung.FieldName = LuuKhoColumns.HanDung.ToString();
            colSoLo.FieldName = LuuKhoColumns.SoLo.ToString();
            colTotal.FieldName = ChiTietPhieuNhapColumns.Total.ToString();
        }

        private void LoadingProductToGrid(SanPham loadingProduct)
        {
            ChiTietPhieuNhap getRow = grvDetail.GetFocusedRow() as ChiTietPhieuNhap;
            bool isNewRow = false;
            if (getRow == null)
            {
                isNewRow = true;
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }
            else if (grvDetail.FocusedRowHandle < 0)
            {
                isNewRow = true;
                m_DetailItemsList.RemoveAt(m_DetailItemsList.Count - 1);
                m_DetailItemsList.RemoveRows.Remove(getRow);
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }

            ClearStatusMessage();
            grvDetail.ClearColumnErrors();

            grvDetail.SetFocusedRowCellValue(colMaThuoc, loadingProduct.MaThuoc);
            getRow.MaKho = CurrentNhapKhoEntry.MaKho;
            grvDetail.SetFocusedRowCellValue(colSoLo, string.Empty);
            grvDetail.SetFocusedRowCellValue(colSoLuong, 0);
            grvDetail.SetFocusedRowCellValue(colDonGia, 0);
            grvDetail.SetFocusedRowCellValue(colNgaySX, null);
            grvDetail.FocusedRowHandle = grvDetail.GetRowHandle(m_DetailItemsList.IndexOf(getRow));
            if (isNewRow == true)
            {
                getRow.CreatedDate = DateTime.Now;
                getRow.RowStatus = (byte)RowStatus.New;
            }
            grvDetail.RefreshEditor(true);
            grvDetail.FocusedColumn = grvDetail.VisibleColumns[0];
        }

        private void LoadingLuuToGrid(LuuKho loadingLuuKho)
        {
            ChiTietPhieuNhap getRow = grvDetail.GetFocusedRow() as ChiTietPhieuNhap;
            bool isNewRow = false;
            if (getRow == null)
            {
                isNewRow = true;
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }
            else if (grvDetail.FocusedRowHandle < 0)
            {
                isNewRow = true;
                m_DetailItemsList.RemoveAt(m_DetailItemsList.Count - 1);
                m_DetailItemsList.RemoveRows.Remove(getRow);
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }

            ClearStatusMessage();
            grvDetail.ClearColumnErrors();

            getRow.MaLuuKho = loadingLuuKho.MaLuuKho;
            getRow.MaThuoc = loadingLuuKho.MaThuoc;
            getRow.MaKho = loadingLuuKho.MaKho;
            getRow.SoLo = loadingLuuKho.SoLo;
            getRow.TonKho = loadingLuuKho.TonKho;
            getRow.NgaySX = loadingLuuKho.NgaySX;
            getRow.HanDung = loadingLuuKho.HanDung;
            getRow.HanSuDung = loadingLuuKho.HanSuDung;
            grvDetail.FocusedRowHandle = grvDetail.GetRowHandle(m_DetailItemsList.IndexOf(getRow));
            if (isNewRow == true)
            {
                getRow.CreatedDate = DateTime.Now;
                getRow.RowStatus = (byte)RowStatus.New;
            }
            grvDetail.RefreshEditor(true);
            grvDetail.FocusedColumn = grvDetail.VisibleColumns[0];
        }

        private void LoadObjectOnForm(string previousCode, string code, IBaseEntity ObjectLoad)
        {
            if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
            {
                if (IsNew)
                {
                    if (ObjectLoad != null)
                    {
                        if (IsDataChanged)
                        {
                            var result = ShowSaveConfimMessage();
                            if (result == DialogResult.Yes)
                            {
                                CurrentNhapKhoEntry.SoPN = previousCode;
                                if (!base.ValidateControls() || !Save())
                                {
                                    return;
                                }
                            }
                        }
                        Entity = ObjectLoad;
                        IsNew = false;
                        IsDataChanged = false;
                    }
                    else
                    {
                        CurrentNhapKhoEntry.SoPN = code;
                        Entity = CurrentNhapKhoEntry;
                        IsNew = true;//important
                        IsDataChanged = true;//important                        
                    }
                }
                else
                {
                    if (!IsDataChanged)
                    {
                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentNhapKhoEntry = new PhieuNhap();
                            CurrentNhapKhoEntry.SoPN = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentNhapKhoEntry;
                            IsNew = true;//important
                            IsDataChanged = true;//important   
                        }
                    }
                    else
                    {
                        var result = ShowSaveConfimMessage();
                        if (result == DialogResult.Yes)
                        {
                            CurrentNhapKhoEntry.SoPN = previousCode;
                            if (!base.ValidateControls() || !Save())
                            {
                                return;
                            }
                        }

                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentNhapKhoEntry = new PhieuNhap();
                            CurrentNhapKhoEntry.SoPN = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentNhapKhoEntry; ;
                            IsNew = true;//important
                            IsDataChanged = true;//important 
                        }
                    }
                }
                ClearErrorMessage();
            }
        }

        private void loadDatasourceCbbKho()
        {
            KhoHangs list = (new KhoHangBO()).GetAllKhoHang();
            m_KhoList = new List<ComboItemExp>();
            foreach (var item in list)
            {
                ComboItemExp tem = new ComboItemExp();
                tem.DisplayValue = item.TenKho;
                tem.ItemValue = item.MaKho;
                m_KhoList.Add(tem);
            }

            cbbMaKho.Properties.Items.AddRange(m_KhoList);
        }

        private void SetKhoCbbData(string code)
        {
            cbbMaKho.SelectedItem = m_KhoList.Find(o => o.ItemValue.ToString().Equals(code,StringComparison.CurrentCultureIgnoreCase));
        }
        #endregion

        private void bteMaPN_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                var form = new NhapKhoLookup();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    IsNew = false;
                    if (form.PhieuNhapSelected != null)
                    {
                        LoadObjectOnForm(bteMaPN.Text.Trim(), form.PhieuNhapSelected.SoPN, form.PhieuNhapSelected);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteMaPN_Leave(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(bteMaPN.Text))
                {
                    if (IsNew)
                    {
                        CurrentNhapKhoEntry.SoPN = NEW_String;
                    }
                    else
                    {
                        DoNew();
                    }
                }else
                {

                    if (CurrentNhapKhoEntry == null) return;
                    string previousCode = DataConvertUltils.ToString(CurrentNhapKhoEntry.SoPN);
                    string code = DataConvertUltils.ToString(bteMaPN.EditValue);
                    if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
                    {
                        PhieuNhap temPhieuNhap = Service.GetPhieuNhapByID(code);
                        if (temPhieuNhap != null)
                        {
                            LoadObjectOnForm(previousCode, code, temPhieuNhap);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteMaKho_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            InventoryLookup form = new InventoryLookup();
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.InventorySelected != null)
                {
                    CurrentNhapKhoEntry.MaKho = form.InventorySelected.MaKho;
                }
            }
        }

        private void bteNhaCC_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            VendorLookup form = new VendorLookup();
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.VendorSelected != null)
                {
                    CurrentNhapKhoEntry.MaNCC = form.VendorSelected.MaNCC;
                }
            }
        }

        private void bteNhaCC_Leave(object sender, EventArgs e)
        {
            try
            {
                string code = DataConvertUltils.ToString(bteNhaCC.EditValue);
                NhaCungCap ncc = (new NhaCungCapBO()).GetNhaCungCapByID(code);
                if (ncc != null)
                {
                    CurrentNhapKhoEntry.MaNCC = ncc.MaNCC;
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void grvDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            ChiTietPhieuNhap row = grvDetail.GetFocusedRow() as ChiTietPhieuNhap;
            if (e.Column == colDonGia || e.Column == colSoLuong)
            {
            }
        }

        private void grvDetail_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if ((e.Info.IsRowIndicator) && (e.RowHandle >= 0))
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void grvDetail_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void grvDetail_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (IsNew)
                {
                    if (this.grvDetail.IsRowSelected(this.grvDetail.FocusedRowHandle) == true)
                    {
                        ChiTietPhieuNhap row = (ChiTietPhieuNhap)this.grvDetail.GetRow(grvDetail.FocusedRowHandle);
                        int index = this.m_DetailItemsList.IndexOf(row);
                        if (index != -1)
                        {
                            bool isNewRow = (row.RowStatus == (byte)RowStatus.New);

                            this.m_DetailItemsList.RemoveAt(index);
                            if (isNewRow == true)
                            {
                                this.m_DetailItemsList.RemoveRows.Remove(row);
                            }
                            base.IsDataChanged = true;


                            decimal total = 0;
                            foreach (ChiTietPhieuNhap item in m_DetailItemsList)
                            {
                                total = total + item.Total;
                            }
                            txtTongTien.EditValue = total;
                        }
                    }
                }
            }
            else if (e.KeyCode == Keys.F3)
            {
                if (this.grvDetail.FocusedColumn == this.colMaThuoc)
                {
                    bteColMaThuoc_ButtonClick(sender, new DevExpress.XtraEditors.Controls.ButtonPressedEventArgs(this.bteColMaThuoc.Buttons[0]));
                }
            }
        }

        private void grvDetail_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ChiTietPhieuNhap sp = grvDetail.GetFocusedRow() as ChiTietPhieuNhap;

            if (sp == null)
            {
                if (grvDetail.FocusedColumn != colMaThuoc)
                {
                    e.Cancel = true;
                }
                else
                {
                    e.Cancel = false;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(sp.MaThuoc))
                {
                    if (grvDetail.FocusedColumn != colMaThuoc)
                    {
                        e.Cancel = true;
                    }
                    else
                    {
                        e.Cancel = false;
                    }
                }
                else
                {
                    e.Cancel = false;
                }
            }


        }

        private void grvDetail_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            ChiTietPhieuNhap currentRow = grvDetail.GetFocusedRow() as ChiTietPhieuNhap;
            DevExpress.XtraGrid.Columns.GridColumn errorColumn = null;
            if (currentRow != null)
            {
                if (currentRow.SoLuong <= 0)
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colSoLuong, Messages.GetString(INVALID_QUANTITY));
                    errorColumn = colSoLuong;
                }

                if (string.IsNullOrEmpty(currentRow.MaThuoc))
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colMaThuoc, Messages.GetString(Constants.REQUIRE_FIELD));
                    errorColumn = colMaThuoc;
                }
                else
                {
                    SanPham tempProduct = ProductService.GetSanPhamByID(currentRow.MaThuoc);
                    if (tempProduct == null)
                    {
                        e.Valid = false;
                        grvDetail.SetColumnError(colMaThuoc, Messages.GetString(PRODUCT_NOT_EXIST));
                        errorColumn = colMaThuoc;
                    }
                }

                if (currentRow.HanSuDung == null && string.IsNullOrEmpty(currentRow.HanDung))
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colHanDung, Messages.GetString(MUST_FILL_HANDUNG_OR_HANSUDUNG));
                    errorColumn = colHanDung;
                }
                
                //if (currentRow.NgaySX == null)
                //{
                //    e.Valid = false;
                //    grvDetail.SetColumnError(colNgaySX, Messages.GetString(Constants.REQUIRE_FIELD));
                //    errorColumn = colNgaySX;
                //}
                //else
                //{
                //    if (currentRow.NgaySX < Constants.MIN_DATE)
                //    {
                //        e.Valid = false;
                //        grvDetail.SetColumnError(colNgaySX, Messages.GetString(Constants.IS_NOT_VALID_DATE_RANGE));
                //        errorColumn = colNgaySX;
                //    }
                //}
                if (currentRow.NgaySX < Constants.MIN_DATE)
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colNgaySX, Messages.GetString(Constants.IS_NOT_VALID_DATE_RANGE));
                    errorColumn = colNgaySX;
                }

                if (string.IsNullOrEmpty(currentRow.SoLo))
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colSoLo, Messages.GetString(Constants.REQUIRE_FIELD));
                    errorColumn = colSoLo;
                }
                else
                {
                    //ChiTietPhieuNhap nhap = (new ChiTietPhieuNhapBO()).GetChiTietPhieuNhapByMaThuocAndSoLo(currentRow.MaThuoc, currentRow.SoLo);
                    //if (nhap != null)
                    //{
                    //    e.Valid = false;
                    //    grvDetail.SetColumnError(colSoLo, Messages.GetString(CHITIETPHIEUNHAP_EXISTED));
                    //    errorColumn = colSoLo;
                    //}
                    //else
                    //{
                    //    if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                    //    {
                    //        int duplicate = -1;
                    //        int index = m_DetailItemsList.IndexOf(currentRow);
                    //        if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                    //        {
                    //            for (int i = 0; i < m_DetailItemsList.Count; i++)
                    //            {
                    //                ChiTietPhieuNhap temprow = m_DetailItemsList[i];
                    //                if (temprow.MaThuoc.Equals(currentRow.MaThuoc, StringComparison.CurrentCultureIgnoreCase) && index != i && temprow.SoLo.Equals(currentRow.SoLo, StringComparison.CurrentCultureIgnoreCase))
                    //                {
                    //                    duplicate = i;
                    //                }
                    //            }
                    //        }

                    //        if (duplicate >= 0)
                    //        {
                    //            grvDetail.SetColumnError(colSoLo, Messages.GetString(DUPLICATE_PRODUCT_CODE));
                    //            e.Valid = false;
                    //            errorColumn = colSoLo;
                    //            m_isDuplicateProduct = true;
                    //        }
                    //        else
                    //        {
                    //            m_isDuplicateProduct = false;
                    //        }
                    //    }
                    //}
                }
            }
            if (errorColumn != null)
            {
                grvDetail.FocusedColumn = errorColumn;
            }
            else
            {
                decimal total = 0;
                foreach (ChiTietPhieuNhap item in m_DetailItemsList)
                {
                    total = total + item.Total;
                }
                txtTongTien.EditValue = total;
            }

            IsLastRowValid = e.Valid;
        }

        private void grvDetail_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            //string solo = null;
            ChiTietPhieuNhap row = grvDetail.GetFocusedRow() as ChiTietPhieuNhap;
            if (grvDetail.FocusedColumn == colSoLuong)
            {
                int qty = DataConvertUltils.ToInt(e.Value);
                if (string.IsNullOrEmpty(row.SoLo))
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colSoLo, Messages.GetString(Constants.REQUIRE_FIELD));
                    DevExpress.XtraGrid.Columns.GridColumn errorColumn = colSoLo;
                    grvDetail.FocusedColumn = errorColumn;
                }
                else if (qty <= 0)
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(INVALID_QUANTITY);
                }                
            }
            else if (grvDetail.FocusedColumn == colMaThuoc)
            {
                string productCode = DataConvertUltils.ToString(e.Value);
                if (string.IsNullOrEmpty(productCode))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                }
                else
                {
                    SanPham temProduct = ProductService.GetSanPhamByID(productCode);
                    if (temProduct == null)
                    {
                        e.Valid = false;
                        e.ErrorText = Messages.GetString(PRODUCT_NOT_EXIST);
                    }
                    else
                    {
                        e.Value = temProduct.MaThuoc;
                        LoadingProductToGrid(temProduct);
                    }
                }
            }
            else if (grvDetail.FocusedColumn == colSoLo)
            {
                string solo = DataConvertUltils.ToString(e.Value);
                if (string.IsNullOrEmpty(solo))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                }
                else
                {
                    LuuKho lk = LuuKhoService.GetLuuKhoByMaThuocAndSoLoAndMaKHo(row.MaThuoc, solo, row.MaKho);
                    if (lk != null)
                    {
                        LoadingLuuToGrid(lk);
                    }

                    ChiTietPhieuNhap row1 = grvDetail.GetFocusedRow() as ChiTietPhieuNhap;
                    for (int i = 0; i < m_DetailItemsList.Count; i++)
                    {
                        if (row1 != m_DetailItemsList[i])
                        {
                            if (solo.Equals(m_DetailItemsList[i].SoLo, StringComparison.CurrentCultureIgnoreCase) && !row1.MaThuoc.Equals(m_DetailItemsList[i].MaThuoc, StringComparison.CurrentCultureIgnoreCase))
                            {
                                e.Valid = false;
                                e.ErrorText = Messages.GetString(DUPLICATE_SOLO);
                            }
                        }
                    }
                }
            }
            else if (grvDetail.FocusedColumn == colNgaySX)
            {
                string ngaysx = DataConvertUltils.ToString(e.Value);
                if (string.IsNullOrEmpty(ngaysx))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                }
                else
                {
                    DateTime date = DataConvertUltils.ToDateTime(e.Value);
                    if (date < Constants.MIN_DATE)
                    {
                        e.Valid = false;
                        e.ErrorText = Messages.GetString(Constants.IS_NOT_VALID_DATE_RANGE);
                    }
                }
            }
        }

        private void bteColMaThuoc_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ChiTietPhieuNhap row = grvDetail.GetFocusedRow() as ChiTietPhieuNhap;
            ProductLookup form = new ProductLookup();
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.ProductSelected != null)
                {
                    LoadingProductToGrid(form.ProductSelected);
                }
            }
        }

        private void bteMaPN_Enter(object sender, EventArgs e)
        {
            if (bteMaPN.Text.Equals(NEW_String))
            {
                bteMaPN.Text = string.Empty;
            }
        }

        private void grvDetail_DataSourceChanged(object sender, EventArgs e)
        {
            decimal total = 0;
            foreach (ChiTietPhieuNhap item in m_DetailItemsList)
            {
                total = total + item.Total;
            }
            txtTongTien.EditValue = total;

        }

        private void cbbMaKho_SelectedValueChanged(object sender, EventArgs e)
        {
            CurrentNhapKhoEntry.MaKho = (string)((ComboItemExp)cbbMaKho.SelectedItem).ItemValue;
        }

        private void dteNgayLap_Leave(object sender, EventArgs e)
        {
            if (dteNgayLap.IsModified)
            {
                CurrentNhapKhoEntry.NgayLapPhieu = dteNgayLap.DateTime;
            }
        }

        private void dteNgayNhap_Leave(object sender, EventArgs e)
        {
            if (dteNgayNhap.IsModified)
            {
                CurrentNhapKhoEntry.NgayNhapKho = dteNgayNhap.DateTime;
            }
        }
    }
}
